import 'package:flutter/material.dart';
import 'package:sample2/pages/samples/popuppage/my_popup_page.dart';

@immutable
class MyPopupTransation extends StatefulWidget {
  final Widget child;

  late AnimationController controller;

  MyPopupTransation({required this.child, super.key});

  AnimationController getAnimationController() {
    //AnimationController 需要放在 StatefulWidget的State 中控制
    return controller;
  }

  @override
  State<StatefulWidget> createState() {
    return MyPopupTransationState();
  }
}

class MyPopupTransationState extends State<MyPopupTransation>
    with SingleTickerProviderStateMixin {
  getAnimationController() {
    widget.controller = AnimationController(
        duration: const Duration(milliseconds: 400), vsync: this)
      ..repeat(reverse: false)
      ..forward();
  }

  @override
  void initState() {
    getAnimationController();
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return SlideTransition(
      position:
          Tween<Offset>(begin: const Offset(0, 1), end: const Offset(0, 0))
              .animate(CurvedAnimation(
                  parent: widget.controller, curve: Curves.easeInOut)),
      child: widget.child,
    );
  }

  @override
  void dispose() {
    super.dispose();
  }
}

///自定義彈出動畫
class MyPopupRoute extends PopupRoute {
  static const String routeName = "/mypopup";

  late MyPopupTransation popupTransation;

  @override
  Widget buildPage(BuildContext context, Animation<double> animation,
      Animation<double> secondaryAnimation) {
    // This method is rerun every time setState is called, for instance as done
    // by the _incrementCounter method above.
    //
    // The Flutter framework has been optimized to make rerunning build methods
    // fast, so that you can just rebuild anything that needs updating rather
    // than having to individually change instances of widgets.
    return MyPopupPage(
      animationController: popupTransation.getAnimationController(),
    );
  }

  @override
  Widget buildTransitions(BuildContext context, Animation<double> animation,
      Animation<double> secondaryAnimation, Widget child) {
    popupTransation = MyPopupTransation(
      child: child,
    );
    return popupTransation;
    // return RotationTransition(
    //     turns: animation,
    //     child: ScaleTransition(
    //       scale: animation,
    //       child: child,
    //     ));
    // return super
    //     .buildTransitions(context, animation, secondaryAnimation, child);
  }

  @override
  Color? get barrierColor => const Color(0x00000000);

  @override
  bool get barrierDismissible => false;

  @override
  String? get barrierLabel => "barrierLabel";

  @override
  Duration get transitionDuration => const Duration(milliseconds: 0);
}
